package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.api.behavior.BehaviorClient;
import com.heima.api.user.IUserClient;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApArticleService;
import com.heima.model.article.dtos.ApArticleDto;
import com.heima.model.article.dtos.ApArticleHomeDto;
import com.heima.model.article.pojos.*;
import com.heima.model.article.vos.ApArticleVo;
import com.heima.model.behavior.dtos.Behavior;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.dtos.LikesDto;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.dtos.UnlikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.utils.common.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2023/3/14 10:06
 * @Version 1.0
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper articleMapper;
    @Autowired
    private ApArticleConfigMapper configMapper;
    @Autowired
    private ApArticleContentMapper contentMapper;
    @Autowired
    private IUserClient iUserRealnameClient;
    @Autowired
    private ApCollectionMapper apCollectionMapper;

    @Autowired
    private BehaviorClient behaviorClient;

    /**
     * 每页默认显示条数
     */
    public final static int DEFAULT_SIZE = 10;
    /**
     * 每页最大显示条数
     */
    public final static int MAX_SIZE = 50;

    @Override
    public ResponseResult load(ApArticleHomeDto dto, Integer loadType) {
        //处理页数
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = DEFAULT_SIZE;
        }
        size = Math.min(size, MAX_SIZE);

        dto.setSize(size);

        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        List<ApArticle> apArticles = articleMapper.loadArticles(dto, loadType);
        List<ApArticleVo> collect = apArticles.stream().map(apArticle -> {
            ApArticleVo apArticleVo = new ApArticleVo();
            BeanUtils.copyProperties(apArticle, apArticleVo);
            apArticleVo.setPublishTime(apArticle.getPublishTime().getTime());
            return apArticleVo;
        }).collect(Collectors.toList());
        return ResponseResult.okResult(collect);
    }

    @Override
    public ResponseResult saveArticle(ApArticleDto articleDto) {
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(articleDto, article);
        article.setPublishTime(new Date());
        if (article.getId() == null) {
            articleMapper.insert(article);
            //保存config
            ApArticleConfig config = new ApArticleConfig(article.getId());
            configMapper.insert(config);

            //保存内容
            ApArticleContent content = new ApArticleContent();
            content.setContent(articleDto.getContent());
            content.setArticleId(article.getId());
            contentMapper.insert(content);
        } else {
            articleMapper.updateById(article);

            ApArticleContent articleContent = contentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, article.getId()));
            articleContent.setContent(articleDto.getContent());
            contentMapper.updateById(articleContent);
        }

        return ResponseResult.okResult(article.getId());
    }

    @Override
    public ResponseResult loadArticleBehavior(UserRelationDto dto) {
        ArticleBehavior articleBehavior = new ArticleBehavior();
        //查询是否关注该文章的作者
        Boolean isfollow = iUserRealnameClient.isFollows(dto);
        articleBehavior.setIsfollow(isfollow);
        //查询是否收藏该文章
        LambdaQueryWrapper<ApCollection> cwrapper = new LambdaQueryWrapper<>();
        cwrapper.eq(ApCollection::getArticleId, dto.getArticleId());
        cwrapper.eq(ApCollection::getEntryId, AppThreadLocalUtil.getUser());
        ApCollection apCollection = apCollectionMapper.selectOne(cwrapper);
        articleBehavior.setIscollection(ObjectUtils.isNotEmpty(apCollection));
        //查询是否点赞该文章
        LikesBehaviorDto likesBehaviorDto = new LikesBehaviorDto();
        likesBehaviorDto.setArticleId(dto.getArticleId());
        Boolean likes = behaviorClient.isLikes(likesBehaviorDto);
        articleBehavior.setIslike(likes);
        //查询是否不喜欢该文章
        UnlikesBehaviorDto unlikesBehaviorDto = new UnlikesBehaviorDto();
        unlikesBehaviorDto.setArticleId(dto.getArticleId());
        Boolean unlikes = behaviorClient.isUnlikes(unlikesBehaviorDto);
        articleBehavior.setIsunlike(unlikes);
        return ResponseResult.okResult(articleBehavior);
    }





    @KafkaListener(topics = "leadnews_likes_topic")
    public void updateArticleLikes(String msg){
        List<LikesDto> likesDtos = JSONArray.parseArray(msg, LikesDto.class);
        if (likesDtos.isEmpty()){return;}
        List<Long> articleIds = likesDtos.stream().map(likesDto -> likesDto.getArticleId()).collect(Collectors.toList());
        List<ApArticle> list = listByIds(articleIds);
        for (ApArticle apArticle : list) {
            for (LikesDto likesDto : likesDtos){
                if (apArticle.getId().equals(likesDto.getArticleId())){
                    apArticle.setLikes(likesDto.getLikesCounts());
                }
            }
        }
        updateBatchById(list);
    }
}